import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_WORKFLOW_API,
  timeout: 20000
})

service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = process.env.VUE_APP_AUTHORIZATION
    config.headers['X-Access-Token'] = process.env.VUE_APP_ACCESSTOKEN
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(response => {
  const res = response.data
  if (res.retCode !== '200') {
    if (res.message && res.message.length > 40) {
      res.message = res.message.substring(0, 40) + '....{请查看日志}'
    }
    Message({ message: res.message, type: 'warning' })
    Promise.reject(new Error(res.message || 'Error'))
  }
  return res
},
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
